var util = require('../system/util');
var db = require('../system/db');

exports.get = function(id, success, error) {
    var params = [id];
    db.query('select * from sys_user where id=?', params, function(err, values, fields) {
        if (err) {
            error(err);
        }
        success(values);
    });
};

exports.login = function(username, password, success, error) {
    var params = [username];
    db.query('select * from sys_user where username=?', params, function(err, values, fields) {
        if (err) {
            error(err);
        }
        var data = {"code": 0};
        if(!values || values.length === 0) {
            data["code"] = -2;
            data["message"] = "不存在该用户";
        } else {
            var newPwd = util.md5(password);
            for(var i = 0; i < values.length; i ++) {
                var user = {id: values[i].id, username: values[i].username, nickname: values[i].nickname};
               if(newPwd === values[i].password) {
                    user.password = undefined;
                    data["code"] = 0;
                    data["body"] = user;
                    break;
               } else {
                    data["code"] = -3;
                    data["message"] = "密码错误";
                    break;
               }
            }
        }
        success(data);
    });
};
